from PyQt5.QtCore import QObject, pyqtSignal

from instruments.my_visa import PVisa


class Instrument(QObject):
    message_emitted = pyqtSignal(str)
    scpi_emitted = pyqtSignal(str)

    def __init__(self, address, parent=None):
        super().__init__(parent)
        self.visa_address = self._create_visa_address(address)
        self._inst = PVisa()
        self._inst_info = []

    @staticmethod
    def _create_visa_address(address):
        """
        Create a VISA address string from a given address.
        """
        if "TCPIP" in address:
            visa_address = "{0}".format(address)
        elif "GPIB" in address:
            visa_address = "{0}".format(address)
        elif "USB" in address:
            visa_address = "{0}".format(address)
        else:
            visa_address = "TCPIP0::{0}::hislip0::INSTR".format(address)
        return visa_address

    def __enter__(self):
        self.connect()
        return self

    def connect(self):
        self._inst.address = self.visa_address
        self._inst_info = self._inst.init()
        if self._inst_info:
            self.message_emitted.emit("Connected to {0}".format(self._inst_info[0]))
            return True
        else:
            self.message_emitted.emit("Failed to connect to {0}".format(self.visa_address))
            return False

    def init(self):
        return self.connect()
